package GoodsService

import (
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/request/GoodsReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-common/BaseService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func TuanDetails(r *ghttp.Request, parames *GoodsReq.TuanDetails) *response.JsonResponse {
	ctx := r.GetCtx()

	// 先取出活动
	var activity *entity.GoodsActivity
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_activity").Where("id", parames.TuanId).Scan(&activity)
	if err != nil {
		return response.FailByRequestMessage(r, "活动不存在")
	}
	var otModel *entity.OrderTuan
	err = toolsDb.GetUnSafaTable(ctx, "order_tuan").Where("tuan_join_id", parames.JoinId).Struct(&otModel)
	if err != nil {
		return response.FailByRequestMessage(r, "活动不存在")
	}
	// 再取出商品
	if otModel.GoodsId != parames.GoodsId {
		return response.FailByRequestMessage(r, "商品信息错误")
	}
	goodsModel, err := GetGoodsModel(ctx, parames.GoodsId)
	if err != nil {
		return response.FailByRequestMessage(r, "商品信息错误")
	}

	where := g.Map{
		"ot.tuan_join_id": parames.JoinId,
		"ot.tuan_type":    1,
		//"ot.status":       1,
	}
	if parames.Type == 0 {
		// 已付款的
		where["o.status = ?"] = 2
	} else {
		// 全部

	}
	// 取出规格
	goodsModel.Specs = getGoodsSpecs(ctx, parames.GoodsId)
	fanhui := g.Map{
		"goods":          goodsModel,
		"photo_base_url": g.Cfg().GetString("site.PhotoUrlProfix"),
		"share_url": BaseService.GetShareUrl(ctx, "tuanShare", g.MapStrStr{
			"joinId":  parames.JoinId,
			"goodsId": gconv.String(parames.GoodsId),
			"tuanId":  gconv.String(parames.TuanId),
		}),
	}
	otList := getGoodsTuanListByWhere(ctx, parames.MemberId, where, 1)
	if len(otList) > 0 {
		// 获取参团列表
		fields := "m.nickname, m.avatar"
		all, err := toolsDb.GetUnSafaTable(ctx, "order_tuan").As("ot").Fields(fields).
			LeftJoin("member m", "ot.member_id = m.id").OrderAsc("ot.id").Where("tuan_join_id", parames.JoinId).
			Where("ot.tuan_type = 2").All()
		if err != nil {
			return response.FailByRequestMessage(r, "获取参团列表失败")
		}
		fanhui["tuan"] = otList[0]

		if all.Len() > 0 {
			fanhui["tuan_list"] = all
		} else {
			// 没有参团列表，给默认显示头像
			tmpList := g.List{}
			for i := 0; i < otList[0].JoinMaxNum-1; i++ {
				tmpList = append(tmpList, g.Map{
					"nickname": "用户",
					"avatar":   g.Cfg().GetString("site.PhotoUrlProfix") + g.Cfg().GetString("site.AvatarUnknownUrl"),
				})
			}
			fanhui["tuan_list"] = tmpList
		}
	}

	return response.SuccessByRequestMessageData(nil, "成功", fanhui)
}

func GetTuanStatusText(status int) string {
	// 0关闭 1拼团中 2团长解散 99成团
	switch status {
	case 0:
		return "已关闭" // 超时
	case 1:
		return "拼团中"
	case 2:
		return "团长解散"
	case 99:
		return "成团"
	}
	return "未知"
}
